package com.situ.vivamarket.api.front;

import com.situ.vivamarket.model.Address;
import com.situ.vivamarket.model.Member;
import com.situ.vivamarket.model.front.MemberAddress;
import com.situ.vivamarket.service.front.MemberAddrService;

import com.situ.vivamarket.service.MemberService;
import com.situ.vivamarket.util.JsonResult;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/front/api/v1/account")
public class AccountApi {
    private MemberAddrService memberAddrService;
    private MemberService memberService;
    @Autowired
    public void setMemberAddrService(MemberAddrService memberAddrService) {
        this.memberAddrService = memberAddrService;
    }
    @Autowired
    public void setMemberService(MemberService memberService) {
        this.memberService = memberService;
    }
//  删除会员地址
    @DeleteMapping
    public ResponseEntity<JsonResult> deleteMemberAddr(Integer id) {
        if(id==null){
            return ResponseEntity.noContent().build();
        }else{
            boolean success=memberAddrService.deleteById(id);
            if(success){
                return ResponseEntity.ok(JsonResult.success("删除收货地址项成功"));
            }else{
                return ResponseEntity.ok(JsonResult.fail("删除收货地址项失败"));
            }
        }
    }

//    修改会员个人信息
    @PutMapping
    public ResponseEntity<JsonResult> updateMember(Member member) {
        if(member==null){
            return ResponseEntity.noContent().build();
        }else{
            boolean success=this.memberService.update(member);
            if(success){
                return ResponseEntity.ok(JsonResult.success("修改账户信息成功"));
            }else{
                return ResponseEntity.ok(JsonResult.fail("修改账户信息失败"));
            }
        }

    }
//    获取省市区的名字，父亲是Null的是省
    @GetMapping("/addr")
    public ResponseEntity<JsonResult> getAddrByParentId(Integer parentId) {
        List< Address> addrs=this.memberAddrService.findAddrByPatentId(parentId);
        if(addrs==null){
            return ResponseEntity.noContent().build();
        }else {
            return ResponseEntity.ok(JsonResult.successData(addrs));
        }
    }

    //    新增会员地址
    @PostMapping
    public ResponseEntity<JsonResult> addMemberAddr(MemberAddress ma, HttpSession session) {
        Member member=(Member) session.getAttribute("current_member_login");
        ma.setMemberId(member.getId());
        boolean success=this.memberAddrService.add(ma);
        if(success){
            return ResponseEntity.ok(JsonResult.successData(ma));
        }else{
            return ResponseEntity.ok(JsonResult.fail("新增收货地址项失败"));
        }
    }
}
